package com.tjec.project.businessWorkbench.controller;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.tjec.common.constant.Constants;
import com.tjec.framework.interceptor.annotation.RepeatSubmit;
import com.tjec.project.businessWorkbench.dto.BmsAttachmentDto;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tjec.framework.aspectj.lang.annotation.Log;
import com.tjec.framework.aspectj.lang.enums.BusinessType;
import com.tjec.framework.security.service.TokenService;
import com.tjec.project.businessWorkbench.domain.BmsBusinessExpertUse;
import com.tjec.project.businessWorkbench.dto.BmsExpertUserDto;
import com.tjec.project.businessWorkbench.service.IBmsBusinessExpertUseService;
import com.tjec.project.businessWorkbench.vo.ExpertAutoExtractVo;
import com.tjec.project.companyLibrary.domain.BmsExpertCompany;
import com.tjec.project.companyLibrary.service.IBmsExpertCompanyService;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsExpertPerson;
import com.tjec.project.projectLeaderWorkbeanch.domain.BmsMdExpertType;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsExpertPersonService;
import com.tjec.project.projectLeaderWorkbeanch.service.IBmsMdExpertTypeService;
import com.tjec.project.system.domain.BmsAttachment;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.common.utils.poi.ExcelUtil;
import com.tjec.framework.web.page.TableDataInfo;

/**
 * 专家使用Controller
 * 
 * @author pangyognfneg
 * @date 2020-04-22
 */
@Api(value="专家使用", tags = {"专家使用接口"})
@RestController
@RequestMapping("/businessWorkbench/expertUse")
public class BmsBusinessExpertUseController extends BaseController
{
    @Autowired
    private IBmsBusinessExpertUseService bmsBusinessExpertUseService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IBmsExpertCompanyService bmsExpertCompanyService;
    @Autowired
    private IBmsExpertPersonService bmsExpertPersonService;
    @Autowired
    private IBmsMdExpertTypeService bmsMdExpertTypeService;

    @Value("${sftp.http}")
    private String http;
    @Value("${sftp.ip}")
    private String ip;

    /**
     * 查询专家使用列表
     */
    @ApiOperation("查询专家使用列表")
    @PreAuthorize("@ss.hasPermi('businessWorkbench:expertUse:list')")
    @GetMapping("/list")
    public TableDataInfo list(BmsBusinessExpertUse bmsBusinessExpertUse)
    {
    	startPage();
        List<BmsBusinessExpertUse> list = bmsBusinessExpertUseService.selectBmsBusinessExpertUseList(bmsBusinessExpertUse);
        return getDataTable(list);
    }

    /**
     * 使用专家-查询专家列表
     */
    @ApiOperation("使用专家-查询专家列表")
    @GetMapping("/expertList")
    public TableDataInfo expertList(BmsBusinessExpertUse bmsBusinessExpertUse)
    {
    	String businessId = bmsBusinessExpertUse.getBusinessId();
        List<String> professionCategorys = bmsMdExpertTypeService.selectBmsMdExpertTypeChildrenByGuid(bmsBusinessExpertUse.getProfessionCategory());
    	startPage();
    	if("0".equals(bmsBusinessExpertUse.getSource())) {//个人专家库
    		BmsExpertPerson bmsExpertPerson = new BmsExpertPerson();
    		bmsExpertPerson.setName(bmsBusinessExpertUse.getName());//姓名
    		bmsExpertPerson.setProfession(bmsBusinessExpertUse.getProfession());//专业
    		bmsExpertPerson.setProfessionalTitle(bmsBusinessExpertUse.getProfessionalTitle());//职称
//    		bmsExpertPerson.setProfessionCategory(bmsBusinessExpertUse.getProfessionCategory());//专业类别
            bmsExpertPerson.setProfessionCategorys(professionCategorys.toArray(new String[professionCategorys.size()]));
            bmsExpertPerson.setBusinessId(businessId);
    		List<BmsExpertPerson> list = bmsExpertPersonService.selectBmsExpertPersonList(bmsExpertPerson);
    		for (BmsExpertPerson expertPerson : list) {
                parsExpertPerson(expertPerson,businessId);
            }
    		return getDataTable(list);
    	}else if("1".equals(bmsBusinessExpertUse.getSource())){//企业专家库
    		BmsExpertCompany bmsExpertCompany = new BmsExpertCompany();
    		bmsExpertCompany.setName(bmsBusinessExpertUse.getName());//姓名
    		bmsExpertCompany.setProfession(bmsBusinessExpertUse.getProfession());//专业
    		bmsExpertCompany.setProfessionalTitle(bmsBusinessExpertUse.getProfessionalTitle());//职称
//    		bmsExpertCompany.setProfessionCategory(bmsBusinessExpertUse.getProfessionCategory());//专业类别
            bmsExpertCompany.setProfessionCategorys(professionCategorys.toArray(new String[professionCategorys.size()]));
            List<BmsExpertCompany> list = bmsExpertCompanyService.selectBmsExpertCompanyList(bmsExpertCompany);
    		for (BmsExpertCompany expertCompany : list) {
                parsExpertCompany(expertCompany,businessId);
            }
    		return getDataTable(list);
    	}else {
    		List<Object> resList = new ArrayList<Object>();
    		BmsExpertPerson bmsExpertPerson = new BmsExpertPerson();
    		bmsExpertPerson.setName(bmsBusinessExpertUse.getName());//姓名
    		bmsExpertPerson.setProfession(bmsBusinessExpertUse.getProfession());//专业
    		bmsExpertPerson.setProfessionalTitle(bmsBusinessExpertUse.getProfessionalTitle());//职称
//    		bmsExpertPerson.setProfessionCategory(bmsBusinessExpertUse.getProfessionCategory());//专业类别
            bmsExpertPerson.setProfessionCategorys(professionCategorys.toArray(new String[professionCategorys.size()]));
            bmsExpertPerson.setBusinessId(businessId);
    		List<BmsExpertPerson> list1 = bmsExpertPersonService.selectBmsExpertPersonList(bmsExpertPerson);
    		for (BmsExpertPerson expertPerson : list1) {
                parsExpertPerson(expertPerson,businessId);
            }
    		resList.addAll(list1);
    		
    		BmsExpertCompany bmsExpertCompany = new BmsExpertCompany();
    		bmsExpertCompany.setName(bmsBusinessExpertUse.getName());//姓名
    		bmsExpertCompany.setProfession(bmsBusinessExpertUse.getProfession());//专业
    		bmsExpertCompany.setProfessionalTitle(bmsBusinessExpertUse.getProfessionalTitle());//职称
//    		bmsExpertCompany.setProfessionCategory(bmsBusinessExpertUse.getProfessionCategory());//专业类别
            bmsExpertCompany.setProfessionCategorys(professionCategorys.toArray(new String[professionCategorys.size()]));
    		List<BmsExpertCompany> list2 = bmsExpertCompanyService.selectBmsExpertCompanyList(bmsExpertCompany);
    		for (BmsExpertCompany expertCompany : list2) {
                parsExpertCompany(expertCompany,businessId);
            }
    		resList.addAll(list2);
    		return getDataTable(resList);
    	}
    }
    
    /**
    *
    * @param expertPerson
    * @return
    */
   public void parsExpertPerson(BmsExpertPerson expertPerson,String businessId){
	   
       if(expertPerson == null){
           return;
       }
       
       BmsExpertUserDto recommand = bmsBusinessExpertUseService.getRecommendCounts(expertPerson.getGuid(), businessId, "0");
       if(recommand.getTotal()>0) {
    	   if(recommand.getRecommendCounts()>0) {
    		   DecimalFormat df = new DecimalFormat("0.00");
    		   String rate = df.format(recommand.getRecommendCounts()*1.0/recommand.getTotal()*100)+"%";
    		   expertPerson.setRecommendRate(rate);
    	   }else {
    		   expertPerson.setRecommendRate("0%");
    	   }
       }
       
       if(StringUtils.isNotBlank(expertPerson.getProfessionCategory())){
           List<BmsMdExpertType> professionCategoryExpertType = bmsMdExpertTypeService.selectBmsMdExpertTypeByGuids(expertPerson.getProfessionCategory().split(";"));
           String professionCategoryNames = "";
           for (BmsMdExpertType bmsMdExpertType : professionCategoryExpertType) {
               professionCategoryNames += bmsMdExpertType.getCname()+";";
           }
           expertPerson.setProfessionCategoryName(professionCategoryNames);
       }
       if(StringUtils.isNotBlank(expertPerson.getProfessionCategory())){
           expertPerson.setProfessionCategorys( expertPerson.getProfessionCategory().split(";"));
       }
       if(StringUtils.isNotBlank(expertPerson.getBusinessMerit())){
           expertPerson.setBusinessMerits( expertPerson.getBusinessMerit().split(";"));
       }
       if(StringUtils.isNotBlank(expertPerson.getIndustryMerit())){
           expertPerson.setIndustryMerits( expertPerson.getIndustryMerit().split(";"));
       }
       if(!CollectionUtils.isEmpty(expertPerson.getBmsAttachments())){
           ArrayList<String> attIds = new ArrayList<>();
           for (BmsAttachment bmsAttachment : expertPerson.getBmsAttachments()) {
        	   if(!"".equals(bmsAttachment.getGuid()) && bmsAttachment.getGuid()!=null) {
        		   attIds.add(bmsAttachment.getGuid());
        	   }
        	   if(!"".equals(bmsAttachment.getStoragePath()) && bmsAttachment.getStoragePath()!=null) {
        		   bmsAttachment.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
        	   }
               
           }
           expertPerson.setAttachmentIds(attIds);
       }
   }
    
    /**
    *
    * @param expertCompany
    * @return
    */
   public void parsExpertCompany(BmsExpertCompany expertCompany,String businessId){
       if(StringUtils.isNotBlank(expertCompany.getProfessionCategory())){
           List<BmsMdExpertType> professionCategoryExpertType = bmsMdExpertTypeService.selectBmsMdExpertTypeByGuids(expertCompany.getProfessionCategory().split(";"));
           String professionCategoryNames = "";
           for (BmsMdExpertType bmsMdExpertType : professionCategoryExpertType) {
               professionCategoryNames += bmsMdExpertType.getCname()+";";
           }
           expertCompany.setProfessionCategoryName(professionCategoryNames);
       }
       
       BmsExpertUserDto recommand = bmsBusinessExpertUseService.getRecommendCounts(expertCompany.getGuid(), businessId, "1");
       if(recommand.getTotal()>0) {
    	   if(recommand.getRecommendCounts()>0) {
    		   DecimalFormat df = new DecimalFormat("0.00");
    		   String rate = df.format(recommand.getRecommendCounts()*1.0/recommand.getTotal()*100)+"%";
    		   expertCompany.setRecommendRate(rate);
    	   }else {
    		   expertCompany.setRecommendRate("0%");
    	   }
       }
       
       if(StringUtils.isNotBlank(expertCompany.getProfessionCategory())){
           expertCompany.setProfessionCategorys( expertCompany.getProfessionCategory().split(";"));
       }
       if(StringUtils.isNotBlank(expertCompany.getBusinessMerit())){
           expertCompany.setBusinessMerits( expertCompany.getBusinessMerit().split(";"));
       }
       if(StringUtils.isNotBlank(expertCompany.getIndustryMerit())){
           expertCompany.setIndustryMerits( expertCompany.getIndustryMerit().split(";"));
       }
       if(!CollectionUtils.isEmpty(expertCompany.getBmsAttachments())){
           ArrayList<String> attIds = new ArrayList<>();
           for (BmsAttachment bmsAttachment : expertCompany.getBmsAttachments()) {
        	   if(!"".equals(bmsAttachment.getGuid()) && bmsAttachment.getGuid()!=null) {
        		   attIds.add(bmsAttachment.getGuid());
        	   }
        	   if(!"".equals(bmsAttachment.getStoragePath()) && bmsAttachment.getStoragePath()!=null) {
        		   bmsAttachment.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
        	   }
               
           }
           expertCompany.setAttachmentIds(attIds);
       }
   }
    
    /**
     * 导出专家使用列表
     */
    @ApiOperation("导出专家使用列表")
   //@PreAuthorize("@ss.hasPermi('businessWorkbench:expertUse:export')")
    @Log(title = "专家使用", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BmsBusinessExpertUse bmsBusinessExpertUse)
    {
        List<BmsBusinessExpertUse> list = bmsBusinessExpertUseService.selectBmsBusinessExpertUseList(bmsBusinessExpertUse);
        ExcelUtil<BmsBusinessExpertUse> util = new ExcelUtil<BmsBusinessExpertUse>(BmsBusinessExpertUse.class);
        return util.exportExcel(list, "专家使用");
    }

    /**
     * 获取专家使用详细信息
     */
    @ApiOperation("获取专家使用详细信息")
    //@PreAuthorize("@ss.hasPermi('businessWorkbench:expertUse:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable("guid") String guid)
    {
        BmsBusinessExpertUse bmsBusinessExpertUse = bmsBusinessExpertUseService.selectBmsBusinessExpertUseByGuid(guid);
        if(!CollectionUtils.isEmpty(bmsBusinessExpertUse.getUseAttachments())){
            ArrayList<String> attIds = new ArrayList<>();
            for (BmsAttachmentDto bmsAttachment : bmsBusinessExpertUse.getUseAttachments()) {
                bmsAttachment.setStoragePath(http + ip + Constants.RESOURCE_PREFIX + bmsAttachment.getStoragePath());
                attIds.add(bmsAttachment.getFileId());
            }
            bmsBusinessExpertUse.setUseAttachmentIds(attIds);
        }
        return AjaxResult.success(bmsBusinessExpertUse);
    }

    /**
     * 新增专家使用
     */
    @ApiOperation("新增专家使用")
    //@PreAuthorize("@ss.hasPermi('businessWorkbench:expertUse:add')")
    @Log(title = "专家使用", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping
    public AjaxResult add(@RequestBody List<BmsBusinessExpertUse> bmsBusinessExpertUses)
    {
    	for (BmsBusinessExpertUse bmsBusinessExpertUse : bmsBusinessExpertUses) {
    		bmsBusinessExpertUse.setCreateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
		}
        return toAjax(bmsBusinessExpertUseService.insertBmsBusinessExpertUse(bmsBusinessExpertUses));
    }

    /**
     * 修改专家使用
     */
    @ApiOperation("修改专家使用")
    //@PreAuthorize("@ss.hasPermi('businessWorkbench:expertUse:edit')")
    @Log(title = "专家使用", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BmsBusinessExpertUse bmsBusinessExpertUse)
    {
    	bmsBusinessExpertUse.setUpdateBy(tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getUserId());
        return toAjax(bmsBusinessExpertUseService.updateBmsBusinessExpertUse(bmsBusinessExpertUse));
    }

    /**
     * 删除专家使用
     */
    @ApiOperation("删除专家使用")
    //@PreAuthorize("@ss.hasPermi('businessWorkbench:expertUse:remove')")
    @Log(title = "专家使用", businessType = BusinessType.DELETE)
	@DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String[] guids)
    {
        return toAjax(bmsBusinessExpertUseService.deleteBmsBusinessExpertUseByGuids(guids));
    }
    
    /**
     * 自动抽取
     */
    @ApiOperation("自动抽取")
    @PostMapping("/autoExtract")
    public AjaxResult autoExtract(@RequestBody ExpertAutoExtractVo expertAutoExtractVos)
    {
    	return AjaxResult.success(bmsBusinessExpertUseService.autoExtract(expertAutoExtractVos));
    }
    
    /**
     * 获取当前项目的项目负责人是否可以使用企业专家库
     */
    @GetMapping(value = "/getIsUseCompanyExpert/{businessId}")
    public AjaxResult getIsUseCompanyExpert(@PathVariable("businessId") String businessId)
    {
        return AjaxResult.success(bmsBusinessExpertUseService.selectIsUseCompanyExpert(businessId));
    }
}
